import {reactive,inject} from "vue"
import app from  '@/app'
export const store = Symbol('state')
export function useInjectState(){
    return inject(store)
}
import {changeSkin, arrFind, jump, arrFindNotChildren, findParent, findIndex,fromHex} from '@/utils/index'
import request from '@/utils/axios'
import token from './token'
import router from '@/router'
import Layout from '@/layout/index.vue'
import Common from '@/layout/common.vue'
import lightTheme from '@/assets/theme/antd.min.glsl?raw';
import darktTheme from '@/assets/theme/antd.dark.min.glsl?raw';
export const state = reactive({
    //语言
    lang:{
        default:'zh-CN',
        list:[],
    },
    //主题色
    theme_color:'#1890ff',
    //布局 default classic
    layout:'default',
    //布局方向 horizontal vertical
    layout_direction:'headerSider',
    //主题 light 暗黑dark
    theme:'light',
    //导航模式 sideTopMenuLayout sideMenuLayout topMenuLayout
    navigationMode:'sideTopMenuLayout',
    //header背景色
    header_background:'#1b253d',
    //header文字颜色
    header_text_color:'#FFFFFF',
    //布局背景色
    layout_background:'#f0f2f5',
    //顶部栏
    header:{
        //文字颜色
        text_color:'#ffffff',
        //选中色
        color:'#1890ff',
        //背景色
        background:'#121929',
    },
    //侧边栏
    sidebar: {
        //文字颜色
        text_color:'#393939',
        //选中色
        color:'#1890ff',
        //背景色
        background:'#121929',
        //宽度
        width:200,
        //是否收起状态
        collapsed: false,
        //显示隐藏
        visible: true,
        //菜单并排数量
        menu_num:1,
    },
    //多页标签
    tabs:true,
    //tab标签
    tabTags:[],
    //顶部菜单选中id
    topMenuSelectKey:null,
    //加载状态
    loading:false,
    //远程加载组件
    component:null,
    //登录路由
    loginRoute:'/common/login',
    //公用渲染路由前缀
    commonRoutePrefix:'common/',
    //后台渲染路由前缀
    adminRoutePrefix:'',
    //语言包
    locale:{},
    //菜单
    menus : [],
    //
    systemInfo:null,
    //主题css
    theme_css: {
        light: '',
        dark: '',
    },
    //隐藏主题
    disableTheme:false,
    //隐藏设置
    disableSetting:false,
    errorData:'',

    isMobile:false,
    modelValue:{},
    modal:[],
})

export const action = {
    //获取系统配置
    getSystemConfig(){
        return new Promise((resolve, reject) =>{
            request({
                url:'/ex-admin/system/config'
            }).then(res=>{
                Object.assign(state,res.data)
                action.changeTheme(state.theme)
                action.changeSiderMenuColor(state.sidebar.background)
                action.changeTopMenuColor(state.header_background)
                action.setSiderMenuNum(state.sidebar.menu_num)
                action.setCommonRoutePrefix(state.commonRoutePrefix)
                action.setAdminRoutePrefix(state.adminRoutePrefix)
                router.addRoute({
                    path: state.loginRoute,
                    component: Common,
                })
                resolve(res)
            }).catch(res=>{
                reject(res)
            })
        })
    },
    //登录
    login(data){
        return new Promise((resolve, reject) =>{
            request({
                url:'/ex-admin/login/check',
                method:'post',
                data:{
                    data:data
                }
            }).then(res => {

                state.tabTags.forEach(item=>{
                    delete app._context.components[item.url]
                })
                state.tabTags = []
                state.systemInfo = null

                token.set(res.data.token)
                resolve(res)
            }).catch(res=>{
                reject(res)
            })
        })
    },
    systemInfo(){
        return new Promise((resolve, reject) =>{
            request({
                url:'/ex-admin/system/info',
            }).then(res => {
                state.systemInfo = res.data
                state.menus = res.data.menu
                resolve(res)
            }).catch(res=>{
                reject(res)
            })
        })
    },
    //退出登录
    logout(url='/'){
        request({
            url:'/ex-admin/login/logout',
        }).then(()=>{
            token.clear()
            router.push(`${state.loginRoute}?redirect=${url}`)
        })
    },
    //切换公用前缀路由
    setCommonRoutePrefix(prefix){
        router.removeRoute('common')
        state.commonRoutePrefix = prefix
        router.addRoute('common',{
            path: '/'+prefix+':pathMatch(.*)',
            component: Common,
        })

    },
    //切换后台前缀路由
    setAdminRoutePrefix(prefix){
        router.removeRoute('admin')
        state.adminRoutePrefix = prefix
        router.addRoute('admin',{
            path: '/'+prefix+':pathMatch(.*)',
            component: Layout,
        })
    },
    //监听路由选中菜单
    watchRouteMenu(path){
        let menu
        if(path === '/'){
            menu = arrFindNotChildren(state.menus)
            if(menu){
                jump(menu.url)
            }
        }else{
            menu = arrFind(state.menus,'url',path.substr(1))
        }
        if(menu){
            if(state.navigationMode == 'topMenuLayout'){
                this.selectTopMenu(menu.id)
            }else{
                let topMenuSelect = findParent(state.menus, menu.pid)

                if(topMenuSelect){
                    this.selectTopMenu(topMenuSelect.id)
                }else{
                    this.selectTopMenu(menu.id)
                }
            }
        }
    },

    //设置菜单
    setMenu(data){
        state.menus = data
    },
    //开关多页标签
    switchTabs(bool){
      state.tabs =  bool
    },
    //切换主题
    changeTheme(theme){
        state.theme = theme
        document.getElementsByTagName("HTML")[0].className = theme+'-theme'
        let content
        if(theme == 'light'){
            content = lightTheme
        }else{
            content = darktTheme
        }
        changeSkin(content,'theme')
    },
    //切换侧边栏背景色
    changeSiderMenuColor(color){
        const content =`:root {--sider-menu-color:${color};}`
        changeSkin(content,'sider-menu')
    },
    openErrorPage(data){
        state.errorData = data
    },
    //切换头部背景色
    changeTopMenuColor(color){
        const content =`:root {--header-menu-color:${color};}`
        changeSkin(content,'top-menu')
    },
    //切换头部文字颜色
    changeTopTextColor(color){
        const content =`:root {--header-text-color:${color};}`
        changeSkin(content,'top-text')
    },
    //切换侧边栏文字颜色
    changeSiderTextColor(color){
        const content =`:root {--sider-text-color:${color};}`
        changeSkin(content,'sider-text')
    },
    //切换布局颜色
    changeLayoutColor(color){
        const content =`:root {--layout-color:${color};}`
        changeSkin(content,'layout-color')
    },
    //设置侧边栏菜单并排数量
    setSiderMenuNum(num){
        const width = Math.trunc(100 / num)
        const content =`:root {--sider-menu-width:${width}%;}`
        changeSkin(content,'sider-num')
    },
    //设置侧边栏菜单选中色
    setSiderMenuSelectedColor(color){
        const rgb = fromHex(color)
        const content =`:root {--sider-menu-selected-color1:${color};--sider-menu-selected-color2:rgba(${rgb.r},${rgb.g},${rgb.b},.2);}`
        changeSkin(content,'sider-menu-selected')
    },
    //设置顶部栏菜单选中色
    setTopMenuSelectedColor(color){
        const content =`:root {--top-menu-selected-color:${color};}`
        changeSkin(content,'top-menu-selected')
    },
    //收缩侧边栏
    collapsed(bool){
        state.sidebar.collapsed = bool
        if(state.isMobile){
            this.sidebarVisible(!bool)
        }
    },
    //侧边栏显示隐藏
    sidebarVisible(bool){
        if(state.isMobile && state.sidebar.collapsed){
            state.sidebar.visible = false
        }else{
            state.sidebar.visible = bool
        }
    },
    //切换设备
    device(value){
        state.isMobile = value
    },
    //选中头部菜单
    selectTopMenu(id){
        state.topMenuSelectKey = id
    },
    //移除
    removeModal(field){
        state.modal.forEach((item,index)=>{
            if(item.field === field){
                state.modal.splice(index,1)
            }
        })
    },
    //刷新
    modalRefresh(params){
        for(let index in state.modal){
            if(state.modal[index].value){
                state.modal[index].modalRefresh(params)
                break
            }
        }
    },
    //远程加载组件
    loadComponent(url,refresh=false){
        return new Promise((resolve, reject) =>{
            state.component = null
            const index = findIndex(state.tabTags,'url',url)
            if(refresh){
                state.tabTags.splice(index,1)
            }
            if(index === -1 || refresh){
                delete app._context.components[url]
                if(refresh){
                    state.loading = true
                }
                request({
                    url:url
                }).then(res=>{
                    const menu = arrFind(state.menus,  'url',url.substr(1))
                    if (menu && state.tabs){
                        state.tabTags.push({
                            name:menu.name,
                            url:url,
                            component:res,
                        })
                    }else{
                        state.component = res
                    }
                    resolve(res)
                }).catch(res=>{
                    resolve(res)
                }).finally(()=>{
                    state.loading = false
                })
            }else{
                resolve()
            }
        })
    }

}
